package org.gw.building.ctrl;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.gw.building.model.Kqy;
import org.gw.building.repositories.dkgg.KqyRepository;
import org.gw.ylc.base.context.RequestContextHolder;
import org.gw.ylc.base.model.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * 考勤员
    * @ClassName: KqyCtrl
    * @author liuyong
    * @date 2017年7月27日
 */
@RestController
@RequestMapping("kq")
public class KqyCtrl {
	@Autowired
	private KqyRepository kqyRepository;
	
	@RequestMapping("getKyqCount")
	@ResponseBody
	public Object getKyqCount(HttpSession session) {
		UserInfo currentUser = (UserInfo) session.getAttribute("_current_user_");
		return kqyRepository.findCountByKqy(currentUser.getUid());
	}

	@RequestMapping(value = "list")
	@ResponseBody
	public Page<Kqy> queryList(String id, String xm) {
		UserInfo userInfo = RequestContextHolder.get().getUser();
		String departmentId = userInfo.getDepartment();
		if (StringUtils.isEmpty(departmentId) && userInfo.getType() != 1) {
			throw new RuntimeException("该用户没有权限");
		}
		Page<Kqy> kqys =  kqyRepository.queryPage(id, xm, RequestContextHolder.get().getPageRequest());
		return kqys;
	}

	@RequestMapping(value = "listUser")
	@ResponseBody
	public Page<Kqy> querylistUser(String kqy) {
		UserInfo userInfo = RequestContextHolder.get().getUser();
		String departmentId = userInfo.getDepartment();
		if (StringUtils.isEmpty(departmentId) && userInfo.getType() != 1) {
			throw new RuntimeException("该用户没有权限");
		}
		if (!StringUtils.isEmpty(kqy)) {
			kqy = "%" + kqy + "%";
		}
		Page<Kqy> kqys =  kqyRepository.queryUserPage(kqy, RequestContextHolder.get().getPageRequest());
		return kqys;
	}

	@RequestMapping("addKqy")
	@Transactional
	@ResponseBody
	public Object addKqy(Kqy entity) {
		if (!StringUtils.isEmpty(entity.getKqyid()) && !StringUtils.isEmpty(entity.getKqyh()) && !StringUtils.isEmpty(entity.getKqy())) {
			return  kqyRepository.save(entity);
		}
		return null;
	}

	@RequestMapping("deleteKqy")
	@ResponseBody
	public Object deleteKqy(String id) {
		try {
			if (!StringUtils.isEmpty(id)) {
				kqyRepository.delete(id);
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
		return id;
	}

}
